/**
 * 执行基本ajax请求,返回XMLHttpRequest
 * Ajax.request(url,{
 *      async   是否异步 true(默认)
 *      method  请求方式 POST or GET(默认)
 *      data    请求参数 (键值对字符串)
 *      success 请求成功后响应函数，参数为xhr
 *      failure 请求失败后响应函数，参数为xhr
 * });
 *
 */
Ajax =
function(){
    function request(url,opt){
        function fn(){}
        var async   = opt.async !== false,
            type    = opt.type      || ''
            method  = opt.method    || 'GET',
            data    = opt.data      || null,
            success = opt.success   || fn,
            failure = opt.failure   || fn;
            method  = method.toUpperCase();
            type  = type.toUpperCase();
        if(method == 'GET' && data){
            url += (url.indexOf('?') == -1 ? '?' : '&') + data;
            data = null;
        }
        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
        xhr.onreadystatechange = function(){
            _onStateChange(xhr,success,failure);
        };
        xhr.open(method,url,async);
        if(type == 'JSON'){
             xhr.setRequestHeader("Content-Type", "application/json");
        }
        else{
            if(method == 'POST'){
                xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;');
            }
        }
        xhr.send(data);
        return xhr;
    }
    function _onStateChange(xhr,success,failure){
        if(xhr.readyState == 4){
            var s = xhr.status;
            if(s>= 200 && s < 300){
                success(xhr);
            }else{
                failure(xhr);
            }
        }else{}
    }
    return {request:request};
}();

function date_to_utc(k, v) {
    var value = this[k];
    if (!(value instanceof Date)) { return v; }

    return openerp.datetime_to_str(value);
}

var genericJsonRpc = function(fct_name, params, fct) {
    var data = {
        jsonrpc: "2.0",
        method: fct_name,
        params: params,
        id: Math.floor(Math.random() * 1000 * 1000 * 1000)
    };
    var xhr = fct(data);
    var result = xhr.pipe(function(result) {
        if (result.error !== undefined) {
            console.error("Server application error", result.error);
            return $.Deferred().reject("server", result.error);
        } else {
            return result.result;
        }
    }, function() {
        //console.error("JsonRPC communication error", _.toArray(arguments));
        var def = $.Deferred();
        return def.reject.apply(def, ["communication"].concat(_.toArray(arguments)));
    });
    // FIXME: jsonp?
    result.abort = function () { xhr.abort && xhr.abort(); };
    return result;
};


var jsonRpc = function(url, fct_name, params, settings) {
    return genericJsonRpc(fct_name, params, function(data) {
        return $.ajax(url, _.extend({}, settings, {
            url: url,
            dataType: 'json',
            type: 'POST',
            data: JSON.stringify(data, date_to_utc),
            contentType: 'application/json'
        }));
    });
};

//接收消息通知（发送方式见bus.bus模块bus.py
//浏览器 openerp.jsonRpc('/longpolling/send','call',{"channel":"c2","message":"m2"});
var WeixinLoginMessager = openerp.Widget.extend({
    init: function(parent, sid, mac, gw_address, gw_port,url,options) {
        this._super(parent);
        this.options = _.clone(options) || {};
        this.sid = sid;
        this.mac = mac;
        this.url = url;
        this.gw_address = gw_address;
        this.gw_port = gw_port;
        this.bus = openerp.bus.bus;
        //this.bus.last = 0;
        this.bus.channels = ['weixin_login','wifidog_auth'];
        this.bus.on("notification", this, this.on_notification);
        openerp.bus.bus.start_polling();
    },

    //消息通知处理函数
    on_notification: function(notification) {
        var self = this;
        var channel = notification[0];
        var message = notification[1];
        if (channel == 'weixin_login'){
            if (this.sid == message.sid){
                $.get("/weixin/check_weixin_session", function(result){
                    if (result == 'OK')
                        setTimeout(function(){
                            $('#img_qr_sid').remove()
                            $('.oe_single_form_container .text-center').text('登录成功, 正在跳转...').css('font-size', '13pt');
                            window.location = '/web';
                        }, 300);
                    else{
                        alert('登录失败\n'+ result);
                    }
                });
            }
        }
        if (channel == 'wifidog_auth'){
            if (this.mac == message.mac){
                window.location = 'http://' + this.gw_address + ':' + this.gw_port + '/wifidog/auth?token=' + message.token+'&url='+this.url;
            }
        }
    },
});



//function check_weixin_session(db) {
//    Ajax.request('/check_weixin_session',{
//            data : '',
//            success : function(xhr){
//                if (xhr.response == 'OK'){
//                    window.location = '/web'
//                }
//                setTimeout(check_weixin_session, 2000);
//            },
//            failure : function(xhr){
//                //to do with xhr
//                setTimeout(check_weixin_session, 2000);
//            }
//        }
//    );
//}

(function() {
    var bus = openerp.bus = {};

    bus.ERROR_DELAY = 10000;

    bus.Bus = openerp.Widget.extend({
        init: function(){
            this._super();
            this.options = {};
            this.activated = false;
            this.channels = [];
            this.last = 0;
            this.stop = false;
        },
        start_polling: function(){
            if(!this.activated){
                this.poll();
                this.stop = false;
            }
        },
        stop_polling: function(){
            this.activated = false;
            this.stop = true;
            this.channels = [];
        },
        poll: function() {
            var self = this;
            self.activated = true;
            var data = {'channels': self.channels, 'last': self.last, 'options' : self.options};
            jsonRpc('/longpolling/poll', 'call', data).then(function(result) {
                _.each(result, _.bind(self.on_notification, self));
                if(!self.stop){
                    self.poll();
                }
            }, function(unused, e) {
                // no error popup if request is interrupted or fails for any reason
                e.preventDefault();
                // random delay to avoid massive longpolling
                setTimeout(_.bind(self.poll, self), bus.ERROR_DELAY + (Math.floor((Math.random()*20)+1)*1000));
            });
        },
        on_notification: function(notification) {
            if (notification.id > this.last) {
                this.last = notification.id;
            }
            this.trigger("notification", [notification.channel, notification.message]);
        },
        add_channel: function(channel){
            if(!_.contains(this.channels, channel)){
                this.channels.push(channel);
            }
        },
        delete_channel: function(channel){
            this.channels = _.without(this.channels, channel);
        },
    });

    // singleton
    bus.bus = new bus.Bus();
    return bus;
})();


window.onload = function(){
    var sid = $('#img_qr_sid').attr('sid');
    //接收消息测试 jsonRpc('/longpolling/poll','call', {"channels":["dftg_message"], last:0}).then(function(r){console.log(r)});
    //发送消息测试 jsonRpc('/longpolling/send','call',{"channel":"dftg_message","message":"m2"});
    var mac = $('#img_qr_sid').attr('mac');
    var gw_port = $('#img_qr_sid').attr('gw_port');
    var gw_address = $('#img_qr_sid').attr('gw_address');
    var url = $('#img_qr_sid').attr('url');
    var dftg_manager = new WeixinLoginMessager(null, sid,mac,gw_address,gw_port,url);
}